﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SPRepository
{
    public class SPGenericDocumentRepository<TT,TD> : SPGenericRepository<TT, TD>
        where TT : IDocumentContentType<TD>, new()
        where TD : class, IDocumentContentTypeDto
    {
        public SPGenericDocumentRepository(SPList list) : base(list)
        {
        }

        public virtual void Create(TD dto, byte[] fileBytes)
        {
            if (List.BaseTemplate != SPListTemplateType.DocumentLibrary)
            {
                throw new InvalidOperationException("This method can only be used on Document Libraries, please use the correct repository type");
            }

            if (dto == null)
            {
                return;
            }

            if (dto.FileName == null)
            {
                throw new ArgumentNullException("dto.FileName cannot be null");
            }

            var contentTypeId = new TT().GetContentTypeIdDefinition();
            var file = List.RootFolder.Files.Add(dto.FileName, fileBytes);
            file.Item["ContentTypeId"] = contentTypeId;
            file.Item.SystemUpdate();
            Update(file.Item, dto);
        }
    }
}
